<template>
  <div class="page-container">
    <div class="tool-container">
      <el-form class="tool-search" :model="queryParams" ref="queryFormRef" :inline="true">
        <el-row>
          <el-form-item prop="regionCode">
            <RegionSelect v-model="queryParams.regionCode" placeholder="行政区域" clearable @change="getVendorList()" />
          </el-form-item>

          <el-form-item prop="vendorId">
            <el-select v-model="queryParams.vendorId" placeholder="酒店名称" clearable>
              <el-option v-for="item in vendors" :key="item.vendorId" :label="item.name" :value="item.vendorId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item prop="room">
            <el-input v-model="queryParams.room" placeholder="房号" clearable @keyup.enter="handleQuery" />
          </el-form-item>

          <el-form-item prop="status">
            <!-- <el-input v-model="queryParams.status" placeholder="状态" clearable @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.status" filterable clearable placeholder="状态">
              <el-option v-for="item in order_status" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="orderType">
            <!-- <el-input v-model="queryParams.orderType" placeholder="订单类型" clearable @keyup.enter="handleQuery" /> -->
            <el-select v-model="queryParams.orderType" filterable clearable placeholder="订单类型">
              <el-option v-for="item in order_type" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item prop="orderId">
            <el-input v-model="queryParams.orderId" placeholder="订单号" clearable />
          </el-form-item>
          <el-form-item prop="hasAccessory">
            <el-select v-model="queryParams.hasAccessory" filterable clearable placeholder="否购买鼻氧">
              <el-option v-for="item in hasAccessory" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item prop="experimentalFlag">
            <el-select v-model="queryParams.experimentalFlag" filterable clearable placeholder="包含调试订单">
              <el-option :value="null" label="全部">全部</el-option>
              <el-option :value="true" label="调试">调试</el-option>
              <el-option :value="false" label="商用">商用</el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
              v-model="times"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY/MM/DD"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery" v-hasPermi="['biz:order:list']">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="primary" icon="Link" @click="exportQuery">导出</el-button>
          </el-form-item>
        </el-row>
      </el-form>
    </div>
    <div class="tabel-container">
      <vxe-grid ref="tableRef" v-bind="gridOptions">
        <template #orderAmount="{ row }">
          {{ row.totalOrderAmount / 100 }}
        </template>
        <template #orderActualPayment="{ row }">
          {{ row.totalOrderActualPayment / 100 }}
        </template>
        <template #refundAmount="{ row }">
          {{ row.refundAmount / 100 }}
        </template>

        <template #position="{ row }">
          <dict-tag :options="room_position" :value="row.roomPosition" />
        </template>
        <template #type="{ row }">
          <dict-tag :options="order_type" :value="row.orderType" />
        </template>
        <template #status="{ row }">
          <dict-tag :options="order_status" :value="row.status" />
        </template>
        <template #hasAccessory="{ row }">
          <el-tag v-if="row.hasAccessory" type="success">购买</el-tag>
          <el-tag v-else type="info">未购买</el-tag>
        </template>
        <template #handle="{ row }">
          <el-button link type="primary" @click="handleDetail(row)" v-hasPermi="['biz:order:query']">详情</el-button>
          <el-button link type="danger" @click="handleCancel(row)" v-hasPermi="['biz:order:edit']">退款</el-button>
        </template>
        <template #bottom>
          <pagination
            v-show="total > 0"
            :total="total"
            v-model:page="queryParams.pageNum"
            v-model:limit="queryParams.pageSize"
            @pagination="getList"
          />
        </template>
      </vxe-grid>
    </div>
    <RefundSet ref="refRefundSet" @success="getList"></RefundSet>
  </div>
</template>

<script setup lang="ts">
import { listOrder, exportOrder } from '@/api/operation/order/index';
import { BizOrderVo } from '@/api/operation/order/types';
import { getTableConfig } from './columns';
import RefundSet from '@/views/operation/order/common/refund-set/index.vue';
import { listVendor } from '@/api/vendor/index';
import { formatDate } from '@vueuse/core';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const gridOptions = reactive(getTableConfig());
const data = toRef(gridOptions, 'data');
const loading = toRef(gridOptions, 'loading');
const { order_type, order_status, room_position } = toRefs<any>(proxy?.useDict('room_position', 'order_status', 'order_type'));

const hasAccessory = [
  { label: '全部', value: null },
  { label: '购买', value: true },
  { label: '未购买', value: false }
];

const total = ref(0);
const vendors = ref([]);

const queryFormRef = ref<ElFormInstance>();

const refRefundSet = ref();

const times = computed({
  get: () => {
    return [queryParams.value.timeRangeStart, queryParams.value.timeRangeEnd];
  },
  set: (v) => {
    if (v == null) {
      queryParams.value.timeRangeStart = null;
      queryParams.value.timeRangeEnd = null;
    } else {
      queryParams.value.timeRangeStart = v[0];
      queryParams.value.timeRangeEnd = v[1];
    }
  }
});

const HXtimeSlotChange = (val) => {
  let startTime, endTime;
  let now = new Date(); //当前日期
  var nowDayOfWeek = now.getDay(); //今天本周的第几天
  var nowDay = now.getDate(); //当前日
  let nowMonth = now.getMonth(); //当前月
  let nowYear = now.getFullYear(); //当前年
  let jd = Math.ceil((nowMonth + 1) / 3);
  switch (val) {
    case 'week':
      startTime = new Date(nowYear, nowMonth, nowDay - nowDayOfWeek);
      endTime = new Date(nowYear, nowMonth, nowDay + (6 - nowDayOfWeek));
    case 'month':
      startTime = new Date(nowYear, nowMonth, 1);
      endTime = new Date(nowYear, nowMonth + 1, 0);
      break;
    case 'year':
      startTime = new Date(nowYear, 0, 1);
      endTime = new Date(nowYear, nowMonth, nowDay);
      break;
  }
  return [startTime, endTime];
};
//格式化日期：yyyy-MM-dd
const formatDate1 = (date) => {
  var myyear = date.getFullYear();
  var mymonth = date.getMonth() + 1;
  var myweekday = date.getDate();
  if (mymonth < 10) {
    mymonth = '0' + mymonth;
  }
  if (myweekday < 10) {
    myweekday = '0' + myweekday;
  }
  return myyear + '-' + mymonth + '-' + myweekday;
};
let week = HXtimeSlotChange('month');
const queryParams = ref<PageQuery>({
  pageNum: 1,
  pageSize: 20,
  status: null,
  orderType: null,
  vendorId: null,
  regionCode: null,
  orderId: null,
  timeRangeStart: formatDate1(week[0]) + ' 00:00:00',
  timeRangeEnd: formatDate1(week[1]) + ' 23:59:59',
  experimentalFlag: false,
  hasAccessory: null
});

/** 查询租户列表 */
const getList = async () => {
  loading.value = true;
  let params = queryParams.value;
  localStorage.setItem('orderQuery', JSON.stringify(params));

  const res = await listOrder(queryParams.value);
  data.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 查询酒店列表 */
const getVendorList = async () => {
  const res = await listVendor({
    pageNum: 1,
    regionCode: queryParams.value.regionCode,
    pageSize: 10000
  });
  vendors.value = res.rows;
};

/** 搜索重置操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();

  let week = HXtimeSlotChange('month');
  nextTick(() => {
    queryParams.value.timeRangeStart = formatDate1(week[0]) + ' 00:00:00';
    queryParams.value.timeRangeEnd = formatDate1(week[1]) + ' 23:59:59';

    handleQuery();
    getVendorList();
  });
};
/** 新增 */
const handleAdd = (row?: BizOrderVo) => {
  proxy?.$modal.msg('TODO是否需要修改功能？');
};
/** 作废 */
const handleCancel = async (row?: BizOrderVo) => {
  refRefundSet.value?.openRefundSet(row);
};
/** 生效 */
const handleTake = async (row?: BizOrderVo) => {
  proxy?.$modal.msg('TODO是否需要修改功能？');
};
/** 详情按钮操作 */
const handleDetail = async (row?: BizOrderVo) => {
  proxy?.$tab.openPage('/operation/orderDetail', '', { id: row?.orderId });
};

/**
 * 导出
 */
const exportQuery = async () => {
  let params = JSON.parse(JSON.stringify(queryParams.value));
  exportOrder(params);

  // loading.value = true;
  // await exportOrder(params)
  //   .then((res) => {
  //     loading.value = false;
  //     let fileName=res.headers['content-disposition'];
  //     let blob = new Blob([res], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
  //     let url = URL.createObjectURL(blob);
  //     window.open(url, '_blank');
  //   })
  //   .catch((e) => {
  //     loading.value = false;
  //   });
};

onMounted(() => {
  let params = localStorage.getItem('orderQuery');
  if (params != null) {
    try {
      queryParams.value = JSON.parse(params);
    } catch (e) {}
  }
  
  getVendorList();
  getList();
});

// onCreated(() => {
//   localStorage.removeItem("orderQuery");
// });
</script>

<style scoped>
.el-form-item {
  padding: 5px;
}

/deep/ .el-date-editor {
  width: 430px;
}
</style>
